package com.example.questionnaires.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.questionnaires.common.Result;
import com.example.questionnaires.common.PageResult;
import com.example.questionnaires.entity.Questionnaire;
import com.example.questionnaires.entity.QuestionnaireRecord;
import com.example.questionnaires.entity.User;
import com.example.questionnaires.exception.BusinessException;
import com.example.questionnaires.service.QuestionnaireService;
import com.example.questionnaires.utils.UserContext;
import com.example.questionnaires.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/api/questionnaire")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true", allowedHeaders = "*", methods = {
    RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS
})
public class QuestionnaireController {
    @Autowired
    private QuestionnaireService questionnaireService;

    @GetMapping("/list")
    public Result<PageResult<Questionnaire>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return questionnaireService.list(page, size);
    }

    @GetMapping("/latest")
    public Result<List<Questionnaire>> latest() {
        try {
            return Result.success(questionnaireService.getLatest());
        } catch (Exception e) {
            log.error("获取最新问卷失败", e);
            return Result.error("获取最新问卷失败");
        }
    }

    @GetMapping("/{id}")
    public Result<QuestionnaireVO> getQuestionnaire(@PathVariable Long id) {
        return questionnaireService.getQuestionnaire(id);
    }

    @PostMapping
    public Result<Void> add(@RequestBody Questionnaire questionnaire) {
        return questionnaireService.add(questionnaire);
    }

    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody Questionnaire questionnaire) {
        questionnaire.setId(id);
        return questionnaireService.update(questionnaire);
    }

    @PutMapping("/{id}/detail")
    public Result<Void> saveDetail(@PathVariable Long id, @RequestBody QuestionnaireDetailVO detail) {
        detail.setId(id);
        questionnaireService.saveDetail(detail);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        return questionnaireService.delete(id);
    }

    @PostMapping("/{id}/submit")
    public Result<Void> submit(@PathVariable Long id, @RequestBody Map<String, Object> answers) {
        try {
            questionnaireService.submitQuestionnaire(id, answers);
            return Result.success();
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("提交问卷失败", e);
            return Result.error("提交失败");
        }
    }

    @GetMapping("/statistics")
    public Result<StatisticsVO> getStatistics() {
        try {
            StatisticsVO statistics = questionnaireService.getStatistics();
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return Result.error("获取统计数据失败");
        }
    }

    @GetMapping("/{id}/statistics")
    public Result<QuestionnaireStatisticsVO> getQuestionnaireStatistics(@PathVariable Long id) {
        try {
            return Result.success(questionnaireService.getQuestionnaireStatistics(id));
        } catch (Exception e) {
            log.error("获取问卷统计数据失败", e);
            return Result.error("获取问卷统计数据失败");
        }
    }

    @PutMapping("/{id}/publish")
    public Result<Void> publish(@PathVariable Long id) {
        return questionnaireService.publish(id);
    }

    @PutMapping("/{id}/end")
    public Result<Void> end(@PathVariable Long id) {
        return questionnaireService.end(id);
    }

    @GetMapping("/my-submissions")
    public Result<List<QuestionnaireSubmissionVO>> getMySubmissions() {
        return Result.success(questionnaireService.getMySubmissions());
    }

    @GetMapping("/{id}/submission")
    public Result<Map<String, Object>> getSubmission(@PathVariable Long id) {
        try {
            User user = UserContext.getCurrentUser();
            if (user == null) {
                return Result.error("请先登录");
            }

            // 获取问卷信息（包含问题和选项）
            QuestionnaireVO questionnaire = questionnaireService.getQuestionnaireDetail(id);
            
            // 获取提交记录
            QuestionnaireRecord record = questionnaireService.getSubmissionByQuestionnaireId(id, user.getId());
            if (record == null) {
                return Result.error("未找到提交记录");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("questionnaire", questionnaire);
            result.put("answers", record.getAnswers());

            return Result.success(result);
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取提交记录失败", e);
            return Result.error("获取提交记录失败");
        }
    }
}
